package com.cyh.forum.controller;

import com.cyh.forum.common.AppResult;
import com.cyh.forum.common.ResultCode;
import com.cyh.forum.config.AppConfig;
import com.cyh.forum.model.Article;
import com.cyh.forum.model.ArticleReply;
import com.cyh.forum.model.User;
import com.cyh.forum.services.IArticleReplyService;
import com.cyh.forum.services.IArticleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


@Api(tags = "回复接口")
@Slf4j
@RestController
@RequestMapping("/reply")

public class ArticleReplyController {

    //  注入service层
    @Resource
    private IArticleReplyService iArticleReplyService;
    @Resource
    private IArticleService iArticleService;


    @ApiOperation("回复帖子")
    @PostMapping("/create")
    public AppResult create(HttpServletRequest request,
                            @ApiParam("帖子ID") @RequestParam("articleId") @NonNull Long articleId,
                            @ApiParam("回复内容") @RequestParam("content") @NonNull String content){
        //  获取用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //  校验用户是否被禁言
        if (user.getState() != 0){
            //  打印日志
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + "userID = " + user.getId());
            //  返回响应
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        //  校验帖子状态
        Article article = iArticleService.selectById(articleId);
        if (article == null || article.getState() != 0 || article.getDeleteState() != 0){
            //  打印日志
            log.warn(ResultCode.FAILED_ARTICLE_NOT_EXISTS.toString() + "articleId = " + article.getId());
            //  返回响应
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        //  设置ArticleReply对象
        ArticleReply articleReply = new ArticleReply();
        articleReply.setArticleId(articleId);
        articleReply.setContent(content);
        articleReply.setPostUserId(user.getId());
        //  调用service层
        iArticleReplyService.create(articleReply);
        //  返回结果
        return AppResult.success();
    }

    @ApiOperation("获取回复列表")
    @GetMapping("/getReplies")
    public AppResult<List<ArticleReply>> getRepliesByArticleId(@ApiParam("帖子ID") @RequestParam("articleId") @NonNull Long articleId){
        //  在service层已经进行过校验了

        //  调用service层 查询结果
        val articleReplies = iArticleReplyService.selectByArticleId(articleId);
        //  返回结果
        return AppResult.success(articleReplies);
    }


}
